import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { ElMessage } from "element-plus";
import { useUserStore } from '@/store';
import { getToken, setToken } from '@/utils/auth';
import router from '@/router';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}
const defaultMsg = '系统开小差，请稍后重试!'
const TOKEN = "x-auth-token";

// axios.defaults.baseURL = '/aaa/v1';
axios.defaults.baseURL = '/api';

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_API_PREFIX_URL;
  // axios.defaults.baseURL = '/aaa/v1';
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // if (config.method === 'get') {
    //   console.log(config, 'config');
    // }
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers[TOKEN] = token;
      // config.headers['accessToken'] = 'c043a1d3691a48a2a6355c83ecba7ffd_5088';
      // config.headers['version'] = '123456';
    }
    return config;
  },
  error => {
    Message.error(error.msg || defaultMsg)
    return Promise.reject(error)
  }
);
// add response interceptors
axios.interceptors.response.use(
  (res: AxiosResponse<HttpResponse>) => {
    const token = res?.headers && res?.headers[TOKEN];
    if( token ){
      setToken(token);
    }
    // console.log(res, '=res');
    const resData = res.data || {}
    const { code, data, msg } = resData;
    if ( code === 200 || code === 0 ) return resData;
    // if ( code === 0 ) return resData;
    if ( code === undefined ) return resData; // 上传、下载文件的接口如果访问正常会直接返回文件数据，不会有code值
    handleError(code, msg);
    return Promise.reject(resData);
  },
  error => {
    Message.error(error.msg || defaultMsg);
    return Promise.reject(error);
  }
)
// 暂时只覆盖了如下部分的code值，可能会有遗漏
function handleError(code: number, msg: string = defaultMsg){
    switch (code) {
        case 503 : 
          ElMessage.error("账户已被冻结");
            break;
        case 410:
        case 412:
        case 501 : 
          ElMessage.error(msg);
          router.push({
            path: '/login'
          });
          break;
        case -1:
          ElMessage.error('服务异常，请联系管理员');
          break;
        default :
          ElMessage.error(msg);
          break;
    }
}


export default axios;